package com.linln.admin.welfare.controller;

import com.linln.admin.welfare.domain.Self;
import com.linln.admin.welfare.domain.Welfare;
import com.linln.admin.welfare.service.SelfService;
import com.linln.admin.welfare.service.WelfareService;
import com.linln.common.enums.StatusEnum;
import com.linln.common.utils.ResultVoUtil;
import com.linln.common.utils.StatusUtil;
import com.linln.common.vo.ResultVo;
import com.linln.component.shiro.ShiroUtil;
import com.linln.modules.system.domain.Dept;
import com.linln.modules.system.service.DeptService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.ExampleMatcher;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author wcy
 * @date 2020/03/14
 */
@Controller
@RequestMapping("/welfare/audit2")
public class Audit2Controller {

    @Autowired
    private WelfareService welfareService;
    @Autowired
    private DeptService deptService;
    @Autowired
    private SelfService selfService;


    /**
     * 跳转到详细页面
     */
    @GetMapping("/detail/{id}")
//    @RequiresPermissions("welfare:audit:detail")
    public String toDetail(@PathVariable("id") Welfare welfare, Model model) {
        model.addAttribute("welfare",welfare);
        return "/welfare/welfare/detail";
    }

    /**
     * 设置一条或者多条数据的状态
     */
    @RequestMapping("/status/{param}")
//    @RequiresPermissions("welfare:audit:status")
    @ResponseBody
    public ResultVo status(
            @PathVariable("param") String param,
            @RequestParam(value = "ids", required = false) List<Long> ids) {
        // 更新状态
        StatusEnum statusEnum = StatusUtil.getStatusEnum(param);
        if (welfareService.updateStatus(statusEnum, ids)) {
            int code = statusEnum.getCode();
            //TODO
            if (code==1){
                for (Long id :ids) {
                    Welfare welfare = welfareService.getById(id);
                    welfare.setMove(ShiroUtil.getSubject().getDept().getPid());
                    welfareService.save(welfare);
                    Self self = selfService.getByUserId(welfare.getUserId());
                    if (self.getMoney()==null) {self.setMoney(0.0);}
                    self.setMoney(self.getMoney()+welfare.getMoney());
                    selfService.save(self);
                }
            }
            return ResultVoUtil.success(statusEnum.getMessage() + "成功");
            //更换所有的流转ID
        } else {
            return ResultVoUtil.error(statusEnum.getMessage() + "失败，请重新操作");
        }
    }
}